package org.ourgrid.broker.business.requester;

import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Map.Entry;

import org.ourgrid.broker.business.dao.BrokerDAOFactory;
import org.ourgrid.broker.business.dao.JobDAO;
import org.ourgrid.broker.business.scheduler.SchedulerIF;
import org.ourgrid.broker.status.JobStatusInfo;
import org.ourgrid.broker.status.JobWorkerStatus;
import org.ourgrid.broker.status.WorkerStatusInfo;
import org.ourgrid.common.internal.IRequestTO;
import org.ourgrid.common.internal.RequesterIF;

public abstract class AbstractBrokerStatusRequester<U extends IRequestTO> implements RequesterIF<U> {
	protected Map<Integer, JobStatusInfo> getAllJobsInfo() {
		JobWorkerStatus jwStatus = null;
		Map<Integer, JobStatusInfo> allJobs = new LinkedHashMap<Integer, JobStatusInfo>();
		Map<Integer, HashSet<WorkerStatusInfo>> allWorkers = new LinkedHashMap<Integer, HashSet<WorkerStatusInfo>>();
		
		JobDAO jobDAO = BrokerDAOFactory.getInstance().getJobDAO();
		
		for(SchedulerIF scheduler: jobDAO.getSchedulers()) {
			jwStatus = scheduler.getCompleteStatus();
			allJobs.putAll(jwStatus.getJobs());
			allWorkers.putAll(convertWorkerStatus(jwStatus.getWorkers()));
		}
		return allJobs;
	}
	
	protected Map<Integer, HashSet<WorkerStatusInfo>> convertWorkerStatus(Map<Integer, WorkerStatusInfo[]> statusMap) {
		
		Map<Integer, HashSet<WorkerStatusInfo>> newMap = new LinkedHashMap<Integer, HashSet<WorkerStatusInfo>>();
		
		if (statusMap != null) {
			for (Entry<Integer, WorkerStatusInfo[]> status : statusMap.entrySet()) {
				newMap.put(status.getKey(), getSet(status.getValue()));
			}
		}
		
		return newMap;
	}
	
	private HashSet<WorkerStatusInfo> getSet(WorkerStatusInfo[] array) {
		
		HashSet<WorkerStatusInfo> set = new LinkedHashSet<WorkerStatusInfo>();
		
		if (array != null) {
			for (WorkerStatusInfo workerStatusInfo : array) {
				set.add(workerStatusInfo);
			}
		}
		
		return set;
	}
}
